# coding:utf8
import pymysql
import yaml
from pathlib import Path
from utils.log_utils import setup_logger

logger = setup_logger()

def connect_database():
    """
    连接数据库
    :return: 数据库连接对象
    """
    config_path = Path("config.yaml")
    with config_path.open('r') as f:
        config = yaml.safe_load(f)
    database_config = config['database']
    try:
        conn = pymysql.connect(
            host=database_config['host'],
            port=database_config['port'],
            user=database_config['user'],
            password=database_config['password'],
            database=database_config['database_name']
        )
        logger.info("成功建立数据库连接")
        return conn
    except pymysql.MySQLError as e:
        logger.error(f"数据库连接出错: {e}")
        return None

def query_database(sql):
    """
    执行数据库查询
    :param sql: SQL查询语句
    :return: 查询结果（通常是列表形式，包含查询到的每一行数据）
    """
    conn = connect_database()
    if conn:
        try:
            cursor = conn.cursor()
            cursor.execute(sql)
            results = cursor.fetchall()
            cursor.close()
            return results
        except pymysql.MySQLError as e:
            logger.error(f"数据库查询出错: {e}")
            return None
        finally:
            conn.close()
    else:
        return None